package rmi.common.ui.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import rmi.common.ui.model.AbstractModel;
import rmi.common.ui.view.AbstractViewPanel;

public abstract class AbstractController implements PropertyChangeListener {

	private List<AbstractViewPanel> registeredViews;
	
	private List<AbstractModel> registerModels;
	
	public AbstractController() {
		this.registeredViews = new ArrayList<AbstractViewPanel>();
		this.registerModels = new ArrayList<AbstractModel>();
	}
	
	public void addModel(AbstractModel model) {
		registerModels.add(model);
		model.addPropertyChangeListener(this);
	}
	
	public void removeModel(AbstractModel model) {
		registerModels.add(model);
		model.removePropertyChangeListener(this);
	}
	
	public void addView(AbstractViewPanel view) {
		registeredViews.add(view);
	}
	
	public void removeView(AbstractViewPanel view) {
		registeredViews.remove(view);
	}
	
	public void propertyChange(PropertyChangeEvent evt) {
		for (AbstractViewPanel view : registeredViews) {
			view.modelPropertyChange(evt);
		}
	}
	
	protected void setModelProperty(String propertyName, Object newValue) {
		for (AbstractModel model : registerModels) {
			try {
				Method method = model.getClass().getMethod("set" + propertyName, newValue.getClass());
				method.invoke(model, newValue);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
